package com.zhugang.week12;

/**
 * @program algorithms
 * @description: moveZeores2
 * @author: chanzhugang
 * @create: 2022/09/07 11:42
 */
public class MoveZeros2 {

    /**
     * 283 移动零
     *
     * @param nums
     */
    public void moveZeros2(int[] nums) {
        // 双指针p（从-1开始）、q, 交换位置
        int p = -1;
        int q = 0;
        while (q < nums.length) {
            if (nums[q] == 0) {
                q++;
                continue;
            }
            if (nums[q] != 0) {
                // 交换非零元素到前面， p+1是下一个非零元素位置
                swap(nums, p + 1, q);
                p++;
                q++;
            }
        }
    }

    private void swap(int[] nums, int p, int q) {
        int temp = nums[p];
        nums[p] = nums[q];
        nums[q] = temp;
    }
}